/*
 * @Author: ygnnli 1585923072@qq.com
 * @Date: 2024-08-15 20:23:08
 * @LastEditors: ygnnli 1585923072@qq.com
 * @LastEditTime: 2024-08-21 09:59:41
 * @FilePath: /bitrpc/source/test_client.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include "../client/requestor.hpp"
#include "../client/rpc_caller.hpp"
#include "../common/dispatcher.hpp"

// void onRpcResponse(const bitrpc::BaseConnection::ptr &conn, bitrpc::RpcResponse::ptr &msg)
// {
//     std::cout << "收到了Rpc响应: ";
//     std::string body = msg->serialize();
//     std::cout << body << std::endl;
// }

// void onTopicResponse(const bitrpc::BaseConnection::ptr &conn, bitrpc::TopicResponse::ptr &msg)
// {
//     std::cout << "收到了Topic响应: ";
//     std::string body = msg->serialize();
//     std::cout << body << std::endl;
// }

void callback(const Json::Value &result)
{
    ILOG("callback  result: %d ",result.asInt());
}
int main()
{
    auto requestor = std::make_shared<bitrpc::client::Requestor>();// 创建Requestor对象
    auto caller = std::make_shared<bitrpc::client::RpcCaller>(requestor);// 创建RpcCaller对象
    
    auto dispatcher = std::make_shared<bitrpc::Dispatcher>();               // 创建Dispatcher对象
    auto rsp_cb = std::bind(&bitrpc::client::Requestor::onResponse, requestor.get(), std::placeholders::_1, std::placeholders::_2); // requestor.get()获取Requestor对象this的指针
    dispatcher->registerHandler<bitrpc::BaseMessage>(bitrpc::MType::RSP_RPC, rsp_cb); // 注册rpc响应映射关系消息处理函数

    auto message_cb = std::bind(&bitrpc::Dispatcher::onMessage, dispatcher.get(), std::placeholders::_1, std::placeholders::_2); // dispatcher.get()获取Dispatcher对象的指针
    auto client = bitrpc::ClientFactory::create("127.0.0.1", 9090);
    client->setMessageCallback(message_cb);
    client->connect();
    
    //同步调用
    auto conn = client->connection();// 获取连接对象
    Json::Value params,result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = caller->call(conn,"Add",params,result);
    if(ret != false)
    {
        ILOG("result: %d ",result.asInt());
    }
    //异步调用
    bitrpc::client::RpcCaller::JsonAsyncResponse res_future;//异步调用结果
    params["num1"] = 55;
    params["num2"] = 21;
    ret = caller->call(conn,"Add",params,res_future);
    if(ret != false)
    {
        result = res_future.get();//获取异步调用结果
        ILOG("result: %d ",result.asInt());
    }
    //回调调用
    params["num1"] = 555;
    params["num2"] = 21;
    ret = caller->call(conn,"Add",params,callback);
    DLOG("---------");


    std::this_thread::sleep_for(std::chrono::seconds(20));
    client->shutdown();
    return 0;
}